package dq.study.concurrent.until;

import java.util.concurrent.CountDownLatch;

/**
 * 1. 主线程输出之前，所有的子线程都等待
 * 2. 所有的子线程执行完之后，主线程继续执行
 *
 * @author dongqun
 * @version 1.0.0
 * @since 2021/08/31 09:49:00
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch done = new CountDownLatch(8);

        for (int i = 0; i < 10; ++i) {
            new Thread(new Worker(start, done)).start();
        }
        System.out.println("main thread do something first");
        start.countDown();
        // 此处按道理应该再所有线程执行完后，继续继续，但实际上报错了
        // fix bug:写错了，将await写成wait了
        done.await();
        System.out.println("main thread continue to do something");
    }


    static class Worker implements Runnable {
        private final CountDownLatch start;
        private final CountDownLatch done;

        Worker(CountDownLatch start, CountDownLatch done) {
            this.start = start;
            this.done = done;
        }

        @Override
        public void run() {
            try {
                start.await();
                System.out.println("worker doing something");
                done.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
